package Thread;

// 自己实现计时器

import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

// 用这个类描述任务
class MyTask implements Comparable<MyTask>{
    private Runnable command; // 描述任务
    private long time; // 多长时间执行任务

    public MyTask(Runnable command, long time) {
        this.command = command;
        // 此处记录的是绝对的时间戳,不是多长时间后执行
        this.time = System.currentTimeMillis() + time;
    }

    public void run() {
        command.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        // 时间小的在前，时间大的在后
        return (int) (this.time - o.time);
    }
}
// 自己创建的定时器类
class MyTimer {
    // 用来阻塞等待的锁对象
    private Object locker = new Object();

    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    public void schedule(Runnable command, long time) {
        MyTask myTask = new MyTask(command, time);
        synchronized (locker) {
            queue.put(myTask);
            locker.notify();
        }
    }

    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                // 循环过程中一直从队首中取出元素
                // 判定队首元素的时间是否就绪，就绪就执行，不就绪就不执行
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTask myTask = queue.take();
                        long curTime = System.currentTimeMillis();
                        if (myTask.getTime() >= curTime) {
                            // 时间还没到
                            queue.put(myTask);
                            locker.wait(myTask.getTime() - curTime);
                        } else {
                            myTask.run();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

public class Demo22 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1111");
            }
        }, 2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2222");
            }
        }, 4000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3333");
            }
        }, 6000);

    }
}
